#!/bin/bash

set -e

SCRIPTPATH=$(pwd -P)
cd "$SCRIPTPATH"

MAVEN_QUIET=""

# Utils
SKIP_CHECKSTYLE=$TRAVIS

# Eclipse
BUILD_ECLIPSE=true

#IntelliJ
BUILD_INTELLIJ=true
INJECT_INTELLIJ_VERSION=false

IJ_VERSION_MAJOR_BUILD=193.5233
IJ_VERSION_MAJOR=2019.3
IJ_VERSION_MINOR=
IJ_VERSION_LATEST=$IJ_VERSION_MAJOR.$IJ_VERSION_MINOR \
                  && [[ -z $IJ_VERSION_MINOR ]] && IJ_VERSION_LATEST=$IJ_VERSION_MAJOR
IJ_SCALA_VERSION_LATEST=2019.3.17

while getopts "hqve:" option; do
  echo $option
    case $option in
        h) echo "usage: $0 [-h] [-q] [-v] [-e eclipse/intellij]"; exit ;;
        q) MAVEN_QUIET="-q" ;;
        v) INJECT_INTELLIJ_VERSION=true ;;
        e)
          shopt -s nocasematch
          case $OPTARG in 
            eclipse) BUILD_ECLIPSE=false ;;
            intellij) BUILD_INTELLIJ=false ;;
          esac ;;
        ?) echo "error: option -$OPTARG is not implemented"; exit ;;
    esac
done

ARTIFACTS_DIR="artifacts"
# check dir exists
if [ ! -d  "$ARTIFACTS_DIR" ]; then
    echo "Creating artifacts directory $ARTIFACTS_DIR"
    mkdir -p $ARTIFACTS_DIR
fi

# echo shell commands when they are executed.
set -x

# Build Utils
echo "Building Utils ..."
mvn install -B -f $SCRIPTPATH/Utils/pom.xml -Dmaven.repo.local=$SCRIPTPATH/.repository -Dcheckstyle.skip=$SKIP_CHECKSTYLE $MAVEN_QUIET
mvn install -B -f $SCRIPTPATH/PluginsAndFeatures/AddLibrary/AzureLibraries/pom.xml -Dmaven.repo.local=$SCRIPTPATH/.repository $MAVEN_QUIET

# Build Eclipse plugin
if $BUILD_ECLIPSE; then
  echo "Building Eclipse plugin ..."
  mvn clean install -B -f $SCRIPTPATH/PluginsAndFeatures/azure-toolkit-for-eclipse/pom.xml $MAVEN_QUIET
  cp ./PluginsAndFeatures/azure-toolkit-for-eclipse/WindowsAzurePlugin4EJ/target/WindowsAzurePlugin4EJ*.zip ./$ARTIFACTS_DIR/WindowsAzurePlugin4EJ.zip
fi

# Build IntelliJ plugin
if $BUILD_INTELLIJ; then
  echo "Building IntelliJ plugin ..."

  ## Build intellij plugin for latest version
  PATCH_PLUGIN_XML_ARGS="" \
    && [ "$INJECT_INTELLIJ_VERSION" == "true" ] && \
      PATCH_PLUGIN_XML_ARGS="-PpatchPluginXmlSinceBuild=$IJ_VERSION_MAJOR_BUILD"

  GRADLE_TASKS="clean buildPlugin bundleBuildIdeaZip"
  GRADLE_ARGS="-s -Pintellij_version=IC-$IJ_VERSION_LATEST -Pdep_plugins=org.intellij.scala:$IJ_SCALA_VERSION_LATEST $PATCH_PLUGIN_XML_ARGS"

  (cd PluginsAndFeatures/azure-toolkit-for-intellij && ./gradlew $GRADLE_TASKS $GRADLE_ARGS)

  cp ./PluginsAndFeatures/azure-toolkit-for-intellij/build/distributions/azure-toolkit-for-intellij.zip ./$ARTIFACTS_DIR/azure-toolkit-for-intellij-$IJ_VERSION_LATEST.zip
  cp ./PluginsAndFeatures/azure-toolkit-for-intellij/build/distributions/ideaIC-bundle-win-x64.zip ./$ARTIFACTS_DIR/ideaIC-bundle-win-x64-$IJ_VERSION_LATEST.zip

fi

echo "ALL BUILD SUCCESSFUL"
